﻿
Imports System.ComponentModel

Public MustInherit Class icomponentPool(Of T As IComponent)
    Inherits pool3(Of T)

    Protected MustOverride Sub eraseImpl(ByRef inst As T)
    Protected MustOverride Sub freeImpl(ByVal inst As T)
    Protected MustOverride Sub inspect(ByVal inst As T)

    Protected NotOverridable Overrides Sub [erase](ByRef inst As T)
        eraseImpl(inst)
        inst.Dispose()
        MyBase.[erase](inst)
    End Sub

    Protected Overridable Function createImpl() As T
        Return alloc(Of T)()
    End Function

    Private Function disposed(ByVal inst As T) As Boolean
        Try
            inspect(inst)
        Catch
            Return True
        End Try
        Return False
    End Function

    Protected NotOverridable Overrides Sub free(ByVal inst As T)
        MyBase.free(inst)
        freeImpl(inst)
        assert(Not disposed(inst))
    End Sub

    Protected NotOverridable Overrides Function create() As T
        Dim rtn As T = Nothing
        rtn = createImpl()
        assert(Not rtn Is Nothing)
        AddHandler rtn.Disposed,
            Sub(sender As Object, e As EventArgs)
                assert(clearing())
            End Sub
        Return rtn
    End Function
End Class
